package ltutils

import (
	"bytes"
	"golang.org/x/text/encoding/simplifiedchinese"
	"golang.org/x/text/transform"
	"io/ioutil"
	"unicode"
)

// IsHanZi 是否是汉字
func IsHanZi(r rune) bool {
	return unicode.Is(unicode.Han, r)
}

// IsStrContainHanZi 字符串是否包含汉字
func IsStrContainHanZi(str string) bool {
	for _, v := range str {
		if IsHanZi(v) {
			return true
		}
	}
	return false
}

// IsAscii 判断是否为ascii码
func IsAscii(r rune) bool {
	return unicode.Is(unicode.ASCII_Hex_Digit, r)
}

func Utf8ToGbk(src string) ([]byte, error) {
	GB18030 := simplifiedchinese.All[0]
	return ioutil.ReadAll(transform.NewReader(bytes.NewBuffer([]byte(src)), GB18030.NewEncoder()))
}

func GbkToUtf8(src []byte) (string, error) {
	GB18030 := simplifiedchinese.All[0]
	b, err := ioutil.ReadAll(transform.NewReader(bytes.NewBuffer(src), GB18030.NewDecoder()))
	return string(b), err
}

// SubStr 截取字符串，支持多字节字符(避免截断含有特殊字符的字符串)
// start：起始下标，负数从从尾部开始，最后一个为-1
// length：截取长度，负数表示截取到末尾
func SubStr(str string, start int, length int) (result string) {
	s := []rune(str)
	total := len(s)
	if total == 0 {
		return
	}
	// 允许从尾部开始计算
	if start < 0 {
		start = total + start
		if start < 0 {
			return
		}
	}
	if start > total {
		return
	}
	// 到末尾
	if length < 0 {
		length = total
	}

	end := start + length
	if end > total {
		result = string(s[start:])
	} else {
		result = string(s[start:end])
	}

	return
}
